/**
 * 
 */
package mblog.web.controller.front.account;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import mblog.core.lang.Consts;
import mblog.core.pojos.User;
import mblog.web.controller.BaseController;
import mtons.modules.pojos.Data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faxsun.core.service.UserService;
import com.faxsun.web.controller.validator.UserRegisterValidator;

/**
 * @author langhsu
 *
 */
@Controller
public class RegController extends BaseController {
	@Autowired
	private UserService userService;

	@Resource(name = "fxInfoUserRegisterValidator")
	private UserRegisterValidator userRegisterValidator;

	@RequestMapping(value = "/reg", method = RequestMethod.GET)
	public String view(@ModelAttribute("user") User user, ModelMap model,
			HttpServletRequest request) {

		if (getProfile() != null) {
			return "redirect:/home";
		}
		// return getView(Views.REG);
		return "/views/reg";
	}

	@RequestMapping(value = "/reg", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Data reg(String username, String password, String name,
			ModelMap model, HttpServletRequest request) {
		Data data = Data.failure("注册失败");
		// String ret = getView(Views.REG);

		try {
			User user = new User();
			user.setUsername(username.trim());
			user.setEmail(username.trim());
			user.setPassword(password.trim());
			user.setName(name.trim());
			user.setAvatar(Consts.avatar);
			userService.register(user);
			data = Data.success("恭喜您! 注册成功");
			/*
			 * UserProfile profile = userService.login(username, password); if
			 * (profile != null) { // record the login status
			 * putProfile(profile); }
			 */
			// ret = getView(Views.REG_RESULT);
			// 设置broadleaf所需要的信息
			// session=request.getSession();
			session.setAttribute("_blc_overrideCustomerId", user.getUid());
			session.setAttribute("OK_TO_USE_SESSION", Boolean.TRUE);
			session.setAttribute("info_first_login", Boolean.TRUE);
		} catch (Exception e) {
			data = Data.failure(e.getMessage());
		}
		model.put("data", data);
		return data;
	}

}
